<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\CityAgentCreateRequest;
use App\Http\Requests\CityAgentUpdateRequest;
use App\Models\City;
use App\Models\CityAgent;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CityAgentController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
       return view('admin.cityAgent.index');
    }
    public function data(Request $request)
    {
        $model = CityAgent::query();
        if ($request->get('name')){
            $model = $model->where('name','like','%'.$request->get('name').'%');
        }
        if ($request->get('phone')){
            $model = $model->where('phone','like','%'.$request->get('phone').'%');
        }
        $res = $model->orderBy('created_at','desc')->paginate($request->get('limit',30))->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $city = $this->cityree();
//        echo "<pre>";
//        print_r($city);
//        exit;
        return view('admin.cityAgent.create', ['city' => $city]);
    }

    public function cityree($list=[], $pk='id', $pid = 'pid', $child = '_child', $root = 0)
    {
        if (empty($list)){
            $list = City::get()->toArray();
        }
        // 创建Tree
        $tree = array();
        if(is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId =  $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                }else{
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CityAgentCreateRequest $request)
    {
        $data = $request->all();
        $data['password'] = bcrypt($data['password']);
        $data['uuid'] = \Faker\Provider\Uuid::uuid();
        if (empty($data['city_id'])) {
            return redirect()->to(route('admin.cityAgent'))->withErrors('系统错误');
        }
        if (CityAgent::create($data)){
            return redirect()->to(route('admin.cityAgent'))->with(['status'=>'添加账号成功']);
        }
        return redirect()->to(route('admin.cityAgent'))->withErrors('系统错误');
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $city = $this->cityree();
        $cityAgent = CityAgent::findOrFail($id);
        return view('admin.cityAgent.edit',[
            'cityAgent' => $cityAgent,
            'city' => $city
        ]);
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(CityAgentUpdateRequest $request, $id)
    {
        $member = CityAgent::findOrFail($id);
        $data = $request->except('password');
        if ($request->get('password')){
            $data['password'] = bcrypt($request->get('password'));
        }
        if ($member->update($data)){
            return redirect()->to(route('admin.cityAgent'))->with(['status'=>'更新用户成功']);
        }
        return redirect()->to(route('admin.cityAgent'))->withErrors('系统错误');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        if (CityAgent::destroy($ids)){
            return response()->json(['code'=>0,'msg'=>'删除成功']);
        }
        return response()->json(['code'=>1,'msg'=>'删除失败']);
    }

    public function getCityAgentIncomeLog()
    {
        return view("admin.cityAgentIncomeLog.index");
    }


    public function getCityAgentIncomeLogData(Request $request)
    {
        $query =  \DB::table("province_agent_income_log as t1")
            ->leftJoin("province_agent as t2","t1.province_agent_id","=", "t2.id")
            ->select("t1.id", "t2.name", "t1.money", "t1.proportion");
        if ($begin_time = $request->input("begin_time")){
           $query = $query->where("t1.created_at",">=", $begin_time);
        }
        if ($end_time = $request->input("end_time"))
        {
            $query = $query->where("t1.created_at", "<", $end_time);
        }
        $per_page = $request->query('per_page', 10);
        $res = $query->paginate($per_page)->toArray();

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }
}
